package xyz.lwm.lazycat.transaction.execute;

import xyz.lwm.lazycat.utility.It;

/**
 * transaction manager
 *
 * @author lwm
 */
public abstract class TransactionManager {

    /**
     * 获取当前事务, 开启或未开启, 事务对象肯定不为空
     *
     * @return 当前事务
     */
    public static Transaction current() {
        return It.of(TransactionLocal.getTransaction()).orElse(TransactionImpl.UNOPENABLE).get();
    }

    /**
     * 开启事务
     *
     * @param tranDefinition 事务定义
     */
    public static void begin(TranDefinition tranDefinition) {
        TransactionImpl transaction = new TransactionImpl(
                tranDefinition.getIsolation(), true, tranDefinition.isReadOnly());
        TransactionLocal.setTransaction(transaction);
    }

    /**
     * 结束事务
     *
     * @param tranDefinition 事务定义
     */
    public static void end(TranDefinition tranDefinition) {
        TransactionLocal.clearTransaction();
    }

    /**
     * 挂起当前事务, 替换成未打开的事务对象
     */
    public static void suspend() {
        TransactionLocal.clearTransaction();
        TransactionLocal.setTransaction(TransactionImpl.UNOPENABLE);
    }

    /**
     * 恢复挂起的事务, 将挂起的事务重新替换
     *
     * @param transaction 挂起的事务
     */
    public static void resume(Transaction transaction) {
        TransactionLocal.clearTransaction();
        TransactionLocal.setTransaction(transaction);
    }

}
